package com.gateWay.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import javax.annotation.Resource;

/**
 * 可以通过配置中心动态刷新gateWay的配置信息
 * @author zdh
 */
@Configuration
@AutoConfigureAfter(GlobalCorsProperties.class)
public class CorsConfig {

  @Resource
  private  GlobalCorsProperties globalCorsProperties;

  @Bean
  public CorsWebFilter corsFilter() {
    UrlBasedCorsConfigurationSource source
            = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    globalCorsProperties.getCorsConfigurations()
            .forEach(source::registerCorsConfiguration);
    return new CorsWebFilter(source);
  }

}